package org.pr.ddddesigner.domain.aggregation.model;

import com.xw.framework.ddd.types.Entity;
import com.xw.framework.infrastructure.config.SpringUtil;
import com.xw.soonmanager.IdConstant;
import lombok.Getter;
import lombok.Setter;
import org.pr.ddddesigner.domain.aggregation.model.repository.UserRepository;
import org.pr.ddddesigner.domain.aggregation.model.transfer.UserEntityToPo;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * @description: 用户模型
 * @projectName:DDD-Designer
 * @see:org.pr.ddddesigner.domain.aggregation.model
 * @author:LXC
 * @createTime:2024/4/17 10:45
 * @version:1.0
 */
@Getter
@Setter
public final class User extends Entity<User.Context> {

    public User(Context context) {
        super(context);
        setUserId(IdConstant.USER_ID);
        setUserName("jack");
        setUserAge(Integer.valueOf(21));
    }

    private UUID userId;
    private String userName;
    private Integer userAge;

    public Mono<User> saveUser() {
        return ctx().repository
                .save(ctx().userEntityToPo.toPo(this))
                .flatMap(userPo -> {
                    return Mono.just(ctx().userEntityToPo.toEntity(userPo));
                });
    }

    public static Factory getFactory() {
        return SpringUtil.getBean(Factory.NAME, Factory.class);
    }

    /**
     * 借助工厂实现依赖注入
     */
    @Component(Factory.NAME)
    public static class Factory implements Entity.Factory {

        private static Context context = new Context();
        public static final String NAME = "userFactory";

        public User make() {
            return new User(context);
        }

        public Factory(
                R2dbcEntityTemplate r2dbcEntityTemplate,
                UserRepository repository,
                UserEntityToPo userEntityToPo
        ) {
            context.r2dbcEntityTemplate = r2dbcEntityTemplate;
            context.repository = repository;
            context.userEntityToPo = userEntityToPo;
        }
    }

    /**
     * 使用Context来分离数据和服务
     */
    public static class Context implements Entity.Context {
        private R2dbcEntityTemplate r2dbcEntityTemplate;
        private UserRepository repository;
        private UserEntityToPo userEntityToPo;
    }
}
